package com.tdk.wifidirectserver.nsd

import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import android.os.Build
import android.util.Log
import java.util.concurrent.Executor
import java.util.concurrent.Executors

/**
 * nsd扫描方,负责扫描nsd
 * @property TAG String
 */
class NsdClient : INsdClient {
    private val TAG = "NsdClient"

    private val executor: Executor = Executors.newSingleThreadExecutor()

    var mNsdServiceInfoFindCallback: (NsdServiceInfo) -> Unit = {}

    var mNsdServiceLostCallback: (NsdServiceInfo) -> Unit = {}
    override fun discoverService(
        context: Context,
        discoveryListener: NsdManager.DiscoveryListener,
        serviceType: String
    ) {
        Log.d(TAG, "$TAG:开始查询")
        var nsdManager: NsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
        try {
            nsdManager.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, discoveryListener)
        } catch (e: Exception) {
            //如果是相同的listener,那么就会报错
            if (e.message.equals("listener already in use")) {
                Log.d(TAG, "$TAG:listener已经在使用")
            }
        }
    }

    override fun stopDiscoverListener(context: Context, listener: NsdManager.DiscoveryListener) {
        var nsdManager: NsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
        nsdManager.stopServiceDiscovery(listener)
    }

    override fun solve(
        context: Context,
        serviceInfo: NsdServiceInfo?,
    ) {
        if (serviceInfo == null) {
            Log.d(TAG, "$TAG:serviceInfo为空")
            return
        }
        var nsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
        if (Build.VERSION.SDK_INT >= 34) {
            nsdManager.registerServiceInfoCallback(
                serviceInfo,
                executor,
                object : NsdManager.ServiceInfoCallback {
                    override fun onServiceInfoCallbackRegistrationFailed(errorCode: Int) {
                        Log.d(TAG, "$TAG:注册失败 $errorCode")
                    }

                    override fun onServiceUpdated(serviceInfo: NsdServiceInfo) {
                        Log.d(TAG, "$TAG:服务更新 ${serviceInfo.serviceName}")
                        mNsdServiceInfoFindCallback.invoke(serviceInfo)
                    }

                    override fun onServiceLost() {
                        Log.d(TAG, "$TAG:服务丢失")
                        mNsdServiceLostCallback.invoke(serviceInfo)
                    }

                    override fun onServiceInfoCallbackUnregistered() {
                        Log.d(TAG, "$TAG:服务信息回调已经注销")
                    }
                }


            )
        } else {
            nsdManager.resolveService(
                serviceInfo,
                object : NsdManager.ResolveListener {
                    override fun onResolveFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) {
                        Log.d(TAG, "$TAG:解析失败 $errorCode")
                    }

                    override fun onServiceResolved(serviceInfo: NsdServiceInfo?) {
                        if (serviceInfo == null) {
                            Log.d(TAG, "$TAG: 服务信息为空")
                            return
                        }
                        Log.d(TAG, "$TAG: 服务信息解析成功 ${serviceInfo.serviceName}")
                        mNsdServiceInfoFindCallback.invoke(serviceInfo)

                    }

                })
        }
    }
}